import * as zrender from 'zrender';
import {
  personColumnWidth,
  barHeight,
  barMargin,
  personColumnZIndex,
} from '../../config';

/**
 * 拖拽手柄的宽度
 */
export const DRAG_HANDLE_WIDTH = 20;

/**
 * 创建拖拽手柄
 * @param zr ZRender实例
 * @param rowIndex 行索引
 * @param y Y坐标
 * @param onReorder 重排序回调函数
 * @param chartState 图表状态对象
 * @param totalRows 总行数
 * @returns 拖拽手柄组
 */
export function createDragHandle(
  zr: any,
  rowIndex: number,
  y: number,
  onReorder: RowReorderCallback,
  chartState: ChartState,
  totalRows: number,
): zrender.Group {
  const dragGroup = new zrender.Group();

  // 设置拖拽手柄初始为隐藏状态
  (dragGroup as any).attr({ invisible: true });

  // 创建拖拽手柄背景
  const handleBackground = new zrender.Rect({
    shape: {
      x: 0,
      y,
      width: DRAG_HANDLE_WIDTH,
      height: barHeight,
    },
    style: {
      fill: 'rgba(100, 100, 100, 0.1)',
      stroke: '#ddd',
      lineWidth: 1,
    },
    z: personColumnZIndex + 1,
    cursor: 'grab',
  });

  // 创建拖拽图标（三条横线）
  const lineSpacing = 4;
  const lineWidth = 12;
  const startX = (DRAG_HANDLE_WIDTH - lineWidth) / 2;
  const startY = y + (barHeight - lineSpacing * 2) / 2;

  for (let i = 0; i < 3; i++) {
    const line = new zrender.Rect({
      shape: {
        x: startX,
        y: startY + i * lineSpacing,
        width: lineWidth,
        height: 2,
      },
      style: {
        fill: '#666',
      },
      z: personColumnZIndex + 2,
      cursor: 'grab',
    });
    dragGroup.add(line);
  }

  dragGroup.add(handleBackground);

  // 添加拖拽逻辑
  setupDragBehavior(dragGroup, zr, rowIndex, onReorder, chartState, totalRows);

  return dragGroup;
}

/**
 * 设置拖拽行为
 * @param dragGroup 拖拽手柄组
 * @param zr ZRender实例
 * @param rowIndex 行索引
 * @param onReorder 重排序回调函数
 * @param chartState 图表状态对象
 * @param totalRows 总行数
 */
function setupDragBehavior(
  dragGroup: zrender.Group,
  zr: any,
  rowIndex: number,
  onReorder: RowReorderCallback,
  chartState: ChartState,
  totalRows: number,
) {
  const dragState: DragState = {
    isDragging: false,
    dragStartIndex: -1,
    dragTargetIndex: -1,
    startY: 0,
    currentY: 0,
  };

  let dragPreview: zrender.Group | null = null;

  dragGroup.on('mousedown', (e: any) => {
    e.event.preventDefault();
    e.event.stopPropagation();

    dragState.isDragging = true;
    dragState.dragStartIndex = rowIndex;
    dragState.dragTargetIndex = rowIndex;
    dragState.startY = e.event.zrY;
    dragState.currentY = e.event.zrY;

    // 改变光标
    (dragGroup as any).attr({ cursor: 'grabbing' });

    // 创建拖拽预览
    createDragPreview(zr, rowIndex, e.event.zrY, chartState);

    // 添加全局事件监听
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
  });

  // 全局鼠标移动事件
  const handleMouseMove = (e: MouseEvent) => {
    if (!dragState.isDragging) {
      return;
    }

    // 获取鼠标在画布中的位置
    const rect = zr.dom.getBoundingClientRect();
    const mouseY = e.clientY - rect.top;
    const mouseX = e.clientX - rect.left;

    dragState.currentY = mouseY;

    // 计算目标行索引
    const targetIndex = calculateTargetIndex(mouseY, chartState, totalRows);

    // 检查鼠标是否在人员列范围内（X轴和Y轴都要检查）
    const isInPersonColumnArea = mouseX >= 0 && mouseX <= personColumnWidth
      && mouseY >= chartState.chartStartY
      && mouseY <= chartState.chartStartY + totalRows * (barHeight + barMargin);

    // 更新拖拽预览位置 - 只在有效行范围内显示
    if (dragPreview) {
      if (targetIndex >= 0 && isInPersonColumnArea) {
        // 在有效范围内，显示拖拽预览并精确定位到目标行
        (dragPreview as any).attr({ invisible: false });

        // 计算目标行的精确Y坐标（对齐到行位置）
        const rowHeight = barHeight + barMargin;
        const targetRowY = chartState.chartStartY + targetIndex * rowHeight - chartState.lastScrollY;

        const previewRect = dragPreview.children()[0] as any;
        if (previewRect) {
          previewRect.attr({
            shape: {
              ...previewRect.shape,
              x: 0,
              y: targetRowY,
              width: chartState.canvasWidth,
            },
          });
        }
      } else {
        // 超出有效范围，隐藏拖拽预览
        (dragPreview as any).attr({ invisible: true });
      }
    }

    if (targetIndex !== dragState.dragTargetIndex) {
      dragState.dragTargetIndex = targetIndex;
      // 暂时注释掉蓝色指示线
      // updateDropIndicator(zr, targetIndex, chartState);
    }
  };

  // 全局鼠标释放事件
  const handleMouseUp = (_e: MouseEvent) => {
    if (!dragState.isDragging) {
      return;
    }

    dragState.isDragging = false;
    (dragGroup as any).attr({ cursor: 'grab' });

    // 执行重排序
    if (dragState.dragTargetIndex !== dragState.dragStartIndex
      && dragState.dragTargetIndex >= 0) {
      onReorder(dragState.dragStartIndex, dragState.dragTargetIndex);
    }

    // 清理拖拽状态
    cleanupDragState();

    // 移除全局事件监听
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  };

  /**
   * 创建拖拽预览
   */
  function createDragPreview(zr: any, _rowIndex: number, y: number, chartState: ChartState) {
    dragPreview = new zrender.Group();

    // 创建半透明的整行预览
    const previewRect = new zrender.Rect({
      shape: {
        x: 0,
        y: y - barHeight / 2,
        width: chartState.canvasWidth,
        height: barHeight,
      },
      style: {
        fill: 'rgba(0, 123, 255, 0.2)',
        stroke: '#007bff',
        lineWidth: 1,
        shadowColor: 'rgba(0, 123, 255, 0.3)',
        shadowBlur: 3,
      },
      z: personColumnZIndex + 10,
    });

    dragPreview.add(previewRect);
    // 确保初始状态是可见的
    (dragPreview as any).attr({ invisible: false });
    zr.add(dragPreview);
  }

  /**
   * 计算目标行索引
   */
  function calculateTargetIndex(mouseY: number, chartState: ChartState, totalRows: number): number {
    const rowHeight = barHeight + barMargin;
    // 考虑图表起始位置和滚动偏移
    // chartState.chartStartY 已经包含了时间轴高度
    const relativeY = mouseY - chartState.chartStartY + chartState.lastScrollY;
    const targetIndex = Math.floor(relativeY / rowHeight);

    // 如果超出有效范围，返回 -1 表示无效位置
    if (targetIndex < 0 || targetIndex >= totalRows) {
      return -1;
    }

    return targetIndex;
  }

  /**
   * 清理拖拽状态
   */
  function cleanupDragState() {
    if (dragPreview) {
      zr.remove(dragPreview);
      dragPreview = null;
    }
  }
}

/**
 * 显示拖拽手柄
 * @param dragHandle 拖拽手柄组
 */
export function showDragHandle(dragHandle: zrender.Group) {
  (dragHandle as any).attr({ invisible: false });
}

/**
 * 隐藏拖拽手柄
 * @param dragHandle 拖拽手柄组
 */
export function hideDragHandle(dragHandle: zrender.Group) {
  (dragHandle as any).attr({ invisible: true });
}
